﻿using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace OfficeMiddlewareCore
{
    public class ExcelHelper
    {
        private ExcelHelper()
        {
        }

        private static ExcelHelper _excelHelper;
        public static ExcelHelper Instance
        {
            get
            {
                if (_excelHelper == null)
                {
                    _excelHelper = new ExcelHelper();
                }
                return _excelHelper;
            }
        }

        /// <summary>
        /// 打开excel文档
        /// </summary>
        /// <returns></returns>
        public void Open(string filePath, Action<bool> savedAction)
        {
            try
            {
                var excel = new Microsoft.Office.Interop.Excel.Application
                {
                    Visible = true
                };
                var wb = excel.Workbooks.Open(filePath);

                if (savedAction != null)
                {
                    wb.BeforeClose += (ref bool cancel) =>
                    {
                        wb.Save();
                        var tempFile =Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("n") );
                        wb.SaveAs(tempFile);
                        savedAction(cancel);
                    };
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);

                throw new CoreException(CoreResponseStatus.打开Word失败, "打开excel失败");
            }
        }


    }
}
